package com.finace.money.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.design.widget.TabLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.finace.money.R;
import com.finace.money.common.util.ACache;
import com.finace.money.common.util.MessageSendUtil;
import com.finace.money.common.util.StringUtil;
import com.finace.money.common.util.TabLayoutUtil;
import com.finace.money.common.util.UIUtil;
import com.finace.money.data.bean.DealInfoBean;
import com.finace.money.data.bean.ExtractTickBean;
import com.finace.money.data.bean.HistoryLineBean;
import com.finace.money.data.bean.StatusListBean;
import com.finace.money.data.bean.TickBean;
import com.finace.money.data.bean.chartbean.MinuteDataBean;
import com.finace.money.di.component.AppComponent;
import com.finace.money.net.socket.PushReceiver;
import com.finace.money.presenter.MinutesViewPresenter;
import com.finace.money.ui.activity.StatusDetalActivity;
import com.finace.money.ui.adapter.DealInfoAdapter;
import com.finace.money.ui.adapter.DealListAdapter;
import com.finace.money.ui.adapter.DealRightListAdapter;
import com.finace.money.ui.widget.chartwidget.ChartConstant;
import com.finace.money.ui.widget.chartwidget.ChartView;
import com.finace.money.ui.widget.chartwidget.CrossView;
import com.finace.money.ui.widget.chartwidget.FenshiView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by zhangpeng on 2017/12/1.
 */

public class MinutesViewFragment extends BaseFragment implements ChartConstant, ChartView.OnDoubleTapListener {


    @BindView(R.id.recycle_status_detail)
    RecyclerView recycleStatusDetail;
    @BindView(R.id.tab_status_detail)
    TabLayout tabStatusDetail;
    @BindView(R.id.cff_fenshiview)
    FenshiView fenshiView;
    @BindView(R.id.cff_cross)
    CrossView crossView;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.text_1)
    TextView text1;
    @BindView(R.id.text_2)
    TextView text2;
    @BindView(R.id.text_3)
    TextView text3;
    @BindView(R.id.text_4)
    TextView text4;
    @BindView(R.id.text_5)
    TextView text5;
    @BindView(R.id.recycle_deal_list)
    RecyclerView recycleDealList;
    @BindView(R.id.tv_current_price)
    TextView tvCurrentPrice;
    @BindView(R.id.tv_current_chp)
    TextView tvCurrentChp;
    @BindView(R.id.tv_current_high)
    TextView tvCurrentHigh;
    @BindView(R.id.tv_current_yestoday)
    TextView tvCurrentYestoday;
    @BindView(R.id.tv_current_have)
    TextView tvCurrentHave;
    @BindView(R.id.tv_current_low)
    TextView tvCurrentLow;
    @BindView(R.id.tv_current_low_count)
    TextView tvCurrentLowCount;
    @BindView(R.id.tv_current_day_add)
    TextView tvCurrentDayAdd;
    @BindView(R.id.tv_ask_price)
    TextView tvAskPrice;
    @BindView(R.id.tv_ask_size)
    TextView tvAskSize;
    @BindView(R.id.tv_bid_price)
    TextView tvBidPrice;
    @BindView(R.id.tv_bid_size)
    TextView tvBidSize;
    @BindView(R.id.tv_info)
    TextView tvInfo;

    private List<TickBean> mTickList = new ArrayList<>();
    private List<DealInfoBean> mDealInfo = new ArrayList<>();
    private DealRightListAdapter dealRightListAdapter;
    private DealListAdapter dealListAdapter;
    private MinutesViewPresenter mMinutesViewPresenter = new MinutesViewPresenter();
    private DealInfoAdapter dealInfoAdapter;
    private StatusListBean mStatusListBean;
    private String mProductID;
    private ArrayList<HistoryLineBean> lineList;
    private int mLevel = 1;
    private MinuteDataBean data;
    private double mPreSettle;

    @Override
    public int setLayout() {
        return R.layout.fragment_minute;
    }

    @Override
    public void init() {

        mStatusListBean = ((StatusDetalActivity) getActivity()).getmStatusListBean();
        mProductID = mStatusListBean.getM_Body().getM_ProductID();
        mPreSettle = mStatusListBean.getM_Body().getM_PreSettle().getM_Value();
        initDealLeftRightView();
        initDealListView();
        initHistory();
        initTab();
        fenshiView.setUsedViews(crossView, tvInfo);
        fenshiView.setOnDoubleTapListener(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PushReceiver.ACTION_HISTORY);
        intentFilter.addAction(PushReceiver.ACTION_TICK);
        intentFilter.addAction(PushReceiver.ACTION_HISTORY_UPDATE);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(historyReceiver, intentFilter);
        unregisterReceiver(historyReceiver);
        showInfo(mStatusListBean.getM_Body().getTickbean());
    }

    private void initHistory() {
        lineList = (ArrayList<HistoryLineBean>) ACache.get(UIUtil.getContext()).getAsObject(mProductID + mLevel);
        if (null != lineList && lineList.size() > 0) {
            showData();
        } else {
            MessageSendUtil.QueryCandle(mLevel,mProductID);
        }

    }

    BroadcastReceiver historyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String finish = intent.getStringExtra(PushReceiver.FINISH);
            String update = intent.getStringExtra(PushReceiver.UPDATE);
            if (StringUtil.isNotNullString(finish) && finish.equals(PushReceiver.FINISH)) {
                lineList = (ArrayList<HistoryLineBean>) ACache.get(UIUtil.getContext()).getAsObject(mProductID + mLevel);
                if (null != lineList && lineList.size() > 0) {
                    showData();
                }
            }
            if(StringUtil.isNotNullString(update) && update.equals(PushReceiver.UPDATE)){
                lineList = (ArrayList<HistoryLineBean>) ACache.get(UIUtil.getContext()).getAsObject(mProductID + mLevel);
                if (null != lineList && lineList.size() > 0) {
                    showData();
                }
            }
            TickBean tickBean = (TickBean) intent.getSerializableExtra(PushReceiver.DATA);

            TickBean remove = null;
            if (null != tickBean && mProductID.equals(tickBean.getSymbol())) {

                showInfo(tickBean);
                if (mTickList.size() == 10) {
                    remove = mTickList.remove(0);
                }
                mTickList.add(tickBean);
                if (null != dealRightListAdapter) {
                    dealRightListAdapter.setmTickBean(remove);
                    dealRightListAdapter.notifyDataSetChanged();
                }
                if (null != dealListAdapter) {
                    dealListAdapter.setmTickBean(remove);
                    dealListAdapter.notifyDataSetChanged();
                }
                mDealInfo = mMinutesViewPresenter.getDealInfoData(lineList, tickBean);
                if (null != dealInfoAdapter) {
                    dealInfoAdapter.notifyDataSetChanged();
                }
            }


        }
    };

    private void showInfo(TickBean payloadBean) {
        if(null == payloadBean){
            return;
        }
        ExtractTickBean  extractTickBean = mMinutesViewPresenter.extractData(payloadBean, mPreSettle,data);
        if(null != extractTickBean){
            if (Double.valueOf(payloadBean.getTrade()) > mPreSettle) {
                tvCurrentPrice.setTextColor(UIUtil.getColor(R.color.colorRedFF3B30));
                tvCurrentChp.setTextColor(UIUtil.getColor(R.color.colorRedFF3B30));
            } else {
                tvCurrentPrice.setTextColor(UIUtil.getColor(R.color.colorGreen4CD964));
                tvCurrentChp.setTextColor(UIUtil.getColor(R.color.colorGreen4CD964));
            }
            tvCurrentPrice.setText(extractTickBean.getCurrentPrice());
            tvCurrentChp.setText(extractTickBean.getCurrentChp());
            tvCurrentHigh.setText(extractTickBean.getCurrentHigh());
            tvCurrentYestoday.setText(extractTickBean.getCurrentYestoday());
            tvCurrentHave.setText(extractTickBean.getCurrentHave());
            tvCurrentLow.setText(extractTickBean.getCurrentLow());
            tvCurrentLowCount.setText(extractTickBean.getCurrentLowCount());
            tvCurrentDayAdd.setText(extractTickBean.getCurrentDayAdd());
            tvAskPrice.setText(payloadBean.getAsk());
            tvAskSize.setText(payloadBean.getAsksize());
            tvBidPrice.setText(payloadBean.getBid());
            tvBidSize.setText(payloadBean.getBidsize());
//            tvInfo.setVisibility(View.VISIBLE);
            tvInfo.setText(Html.fromHtml(extractTickBean.getInfo()));

        }
    }

    private void showData() {
        data = mMinutesViewPresenter.getData(lineList,mPreSettle);
        fenshiView.setDataAndInvalidate(data);
    }

    private void initDealLeftRightView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(UIUtil.getContext(), LinearLayoutManager.VERTICAL, false);
        recycleStatusDetail.setLayoutManager(linearLayoutManager);
        dealRightListAdapter = new DealRightListAdapter();
        dealRightListAdapter.setmTickList(mTickList);
        recycleStatusDetail.setAdapter(dealRightListAdapter);
    }

    private void initTab() {

        tabStatusDetail.addTab(tabStatusDetail.newTab().setText(R.string.deal_detail));
        tabStatusDetail.addTab(tabStatusDetail.newTab().setText(R.string.disk_information));
        TabLayoutUtil.reflex(tabStatusDetail);

        tabStatusDetail.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0://成交明细
                        initDealListView();
                        break;
                    case 1://盘口信息
                        initDealInfoView();
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    /**
     * 盘口信息
     */
    private void initDealInfoView() {
        llTitle.setVisibility(View.GONE);
        viewLine.setVisibility(View.GONE);
        recycleDealList.setPadding(UIUtil.dip2px(8), UIUtil.dip2px(10), UIUtil.dip2px(8), 0);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(UIUtil.getContext(), 3, GridLayoutManager.VERTICAL, false);
        recycleDealList.setLayoutManager(gridLayoutManager);
        dealInfoAdapter = new DealInfoAdapter();
        dealInfoAdapter.setmData(mDealInfo);
        recycleDealList.setAdapter(dealInfoAdapter);
    }

    /**
     * 成交明细
     */
    private void initDealListView() {
        llTitle.setVisibility(View.VISIBLE);
        viewLine.setVisibility(View.VISIBLE);
        recycleDealList.setPadding(0, 0, 0, 0);
        text1.setTextSize(12);
        text2.setTextSize(12);
        text3.setTextSize(12);
        text4.setTextSize(12);
        text5.setTextSize(12);
        text1.setTextColor(UIUtil.getColor(R.color.colorWhite899198));
        text2.setTextColor(UIUtil.getColor(R.color.colorWhite899198));
        text3.setTextColor(UIUtil.getColor(R.color.colorWhite899198));
        text4.setTextColor(UIUtil.getColor(R.color.colorWhite899198));
        text5.setTextColor(UIUtil.getColor(R.color.colorWhite899198));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(UIUtil.getContext(), LinearLayoutManager.VERTICAL, false);
        recycleDealList.setLayoutManager(linearLayoutManager);
        dealListAdapter = new DealListAdapter();
        dealListAdapter.setmTickList(mTickList);
        recycleDealList.setAdapter(dealListAdapter);
    }

    @Override
    public void setupAcitivtyComponent(AppComponent appComponent) {

    }

    @Override
    public void onDoubleTap() {
        fenshiView.getParent().requestDisallowInterceptTouchEvent(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        isPause = false;
//        refrushHandler.sendEmptyMessageDelayed(0, REFRUSH_TIME);
    }

    @Override
    public void onPause() {
        super.onPause();
        isPause = true;
    }

    protected boolean isShow;

    private boolean isPause;

    public static final int REFRUSH_TIME = 10000;

    /*private Handler refrushHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (isShow && !isPause) {

            }
            if (!isPause) {
                refrushHandler.sendEmptyMessageDelayed(0, REFRUSH_TIME);
            }
        }
    };*/
}
